package cn.smdq.ch.upms.admin.pay.service;

import cn.smdq.ch.common.constant.CommonConstants;
import cn.smdq.ch.common.util.ResultUtil;
import cn.smdq.ch.common.vo.Result;
import cn.smdq.ch.upms.admin.pay.body.PayBody;
import cn.smdq.ch.upms.admin.pay.channel.PayChannel;
import cn.smdq.ch.upms.admin.pay.channel.RoutePayChannel;
import cn.smdq.ch.upms.admin.pay.channel.param.AliPayConstants;
import cn.smdq.ch.upms.admin.pay.channel.param.AliPayPrePayResponse;
import cn.smdq.ch.upms.admin.pay.channel.param.PrePayResponse;
import cn.smdq.ch.upms.admin.pay.type.PayType;
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Service;

/**
 * @author shuimodanqing
 * create at:  2019/1/29  3:02 PM
 * @description 支付业务
 */
@Service
public class PayService {


    public Result pay(PayBody payBody) {

        PayChannel payChannel = new RoutePayChannel(PayType.ALI_PAY_WAP, buildPayParam(payBody));
        PrePayResponse response = payChannel.pay(PayType.ALI_PAY_WAP);
        String result = "";
        if (response.getResponse() instanceof AliPayPrePayResponse) {
            //创建支付记录
            AliPayPrePayResponse payResponse = (AliPayPrePayResponse) response.getResponse();
            result = payResponse.getBody();
            System.out.println("pay Url: " + result);
        }
        return ResultUtil.ok(result);
    }

    private JSONObject buildPayParam(PayBody payBody) {
        JSONObject param = new JSONObject();
        param.put("appId", AliPayConstants.appId);
        param.put("gateWay", AliPayConstants.gateWay);
        param.put("privateKey", AliPayConstants.privateKey);
        param.put("format", AliPayConstants.format);
        param.put("charset", AliPayConstants.charset);
        param.put("publicKey", AliPayConstants.publicKey);
        param.put("signType", AliPayConstants.signType);
        param.put("body", payBody.getBody());
        param.put("subject", payBody.getSubject());
        param.put("totalFee", payBody.getAmount());
        param.put("currency", "cny");
        param.put("payType", "ALI_PAY_WAP");
        param.put("clientIp", "127.0.0.1");
        param.put("device", "app");
        param.put("notifyUrl", "https://www.smdq-ch.cn/admin/pay/app/aliPay/notify");
        param.put("outTradeNo", CommonConstants.ORDER_NO_PREFIX + String.valueOf(System.currentTimeMillis()));
        return param;
    }
}
